/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.beepmystuff;

/**
 * An exception representing a failure to communicate with the BMS server due to
 * an API error.
 */
@SuppressWarnings("serial")
public class BmsApiException extends BmsException {
  private final ErrorCode errorCode;

  enum ErrorCode {
    /** Success. */
    SUCCESS(-0),
    /** Invalid developer key. */
    INVALID_KEY(-1),
    /** Invalid username or password. */
    INVALID_USERNAME(-2),
    /** Invalid session. The session is unknown or has expired. */
    INVALID_SESSION(-3),
    /** Invalid EAN/UPC. */
    INVALID_EAN(-4),
    /** Missing required argument. */
    MISSING_ARGUMENT(-5);

    int number;

    ErrorCode(int number) {
      this.number = number;
    }

    public int getNumber() {
      return number;
    }

    /**
     * Returns the ErrorCode with the given error number, or null if no such
     * ErrorCode exists.
     */
    public static ErrorCode valueOf(int number) {
      for (ErrorCode e : ErrorCode.values()) {
        if (e.number == number) {
          return e;
        }
      }
      return null;
    }
  }

  /**
   * Constructs a new BmsApiException with the given API error code and error
   * message.
   */
  public BmsApiException(ErrorCode errorCode, String reason) {
    super(reason);
    this.errorCode = errorCode;
  }

  /**
   * Constructs a new BmsApiException with the given API error code and error
   * message.
   */
  public BmsApiException(ErrorCode errorCode, String reason, Throwable cause) {
    super(reason, cause);
    this.errorCode = errorCode;
  }

  /** Returns the BMS API error code. */
  public ErrorCode getErrorCode() {
    return errorCode;
  }

  @Override
  public String toString() {
    return super.toString() + " errorCode: " + errorCode;
  }
}
